package user

import (
	"context"
	"fmt"
	"github.com/zeromicro/go-zero/core/stores/sqlc"
	"strconv"

	"go-admin/base/internal/svc"
	"go-admin/base/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *LoginLogic) Login(req *types.UserLoginReqDTO) (resp *types.UserStringRespDTOS, err error) {
	// todo: add your logic here and delete this line
	user, err := l.svcCtx.UserModel.FindOneByUserNum(l.ctx, req.UserNum)
	if err != nil {
		if err == sqlc.ErrNotFound {
			return &types.UserStringRespDTOS{
				Data: "",
				Result: types.Result{
					Code:    444,
					Message: "账号不存在！" + req.UserNum,
				},
			}, nil

		} else {
			fmt.Errorf(err.Error())
			return nil, err
		}
	}
	if user.Password.String != req.Password {
		return &types.UserStringRespDTOS{
			Data: "",
			Result: types.Result{
				Code:    444,
				Message: "密码错误！" + req.UserNum,
			},
		}, nil
	}

	return &types.UserStringRespDTOS{
		Data: strconv.FormatInt(user.Id, 10),
		Result: types.Result{
			Code: 200,
		},
	}, nil
}
